<!-- auth-server/public/login.html -->
<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>统一认证中心 - 登录</title>
  <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-100 min-h-screen flex items-center justify-center">
  <div class="bg-white p-8 rounded-lg shadow-md w-full max-w-md">
    <h2 class="text-2xl font-bold text-center mb-6">统一认证中心</h2>
    
    <form id="loginForm" class="space-y-4">
      <div>
        <label class="block text-sm font-medium text-gray-700">用户名</label>
        <input type="text" name="username" required
               class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500">
      </div>
      
      <div>
        <label class="block text-sm font-medium text-gray-700">密码</label>
        <input type="password" name="password" required
               class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500">
      </div>
      
      <div class="text-red-500 text-sm hidden" id="errorMsg"></div>
      
      <button type="submit" 
              class="w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
        登录
      </button>
    </form>
  </div>

  <script>
    // 从URL获取回调地址
    const urlParams = new URLSearchParams(window.location.search);
    const redirectUrl = urlParams.get('redirectUrl');

    document.getElementById('loginForm').addEventListener('submit', async (e) => {
      e.preventDefault();
      const errorMsg = document.getElementById('errorMsg');
      errorMsg.classList.add('hidden');

      try {
        // 收集表单数据
        const formData = new FormData(e.target);
        const data = {
          username: formData.get('username'),
          password: formData.get('password'),
          redirectUrl: redirectUrl || 'http://localhost:3001' // 默认回调到应用1
        };

        // 调用登录接口
        const response = await fetch('http://localhost:3000/login', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(data),
          credentials: 'include' // 允许跨域携带Cookie（存储refreshToken）
        });

        const result = await response.json();
        if (!response.ok) throw new Error(result.message || '登录失败');

        // 登录成功，跳回原应用并携带accessToken
        window.location.href = `${result.redirectUrl}?accessToken=${result.accessToken}`;
      } catch (err) {
        errorMsg.textContent = err.message;
        errorMsg.classList.remove('hidden');
      }
    });
  </script>
</body>
</html>